# -*- coding: utf-8 -*-
# filename: handle.py

import hashlib
import web
import reply
import receive
import get_coin_info

class Handle(object):
    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "hello, this is handle view"
            signature = data.signature
            timestamp = data.timestamp
            nonce = data.nonce
            echostr = data.echostr
            token = "1234" #请按照公众平台官网\基本配置中信息填写

            list = [token, timestamp, nonce]
            list.sort()
            tmp_str = "".join(list)
            tmp_str = tmp_str.encode('utf-8')
            hashcode = hashlib.sha1(tmp_str).hexdigest()
            print("handle/GET func:")
            print("  hashcode:", hashcode)
            print(" signature:", signature)
            if hashcode == signature:
                print("verify ok")
                return echostr
            else:
                print("verify fail")
                return ""
        except:
            print("exception error!")
            return 0

    def POST(self):
        try:
            webData = web.data()
            print("Handle Post webdata is ", webData)
            #后台打日志
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                data = str(recMsg.Content, 'utf-8')
                print(data)
                if (data.isalpha()):
                    coin = get_coin_info.coin_info(data)
                else:
                    coin = get_coin_info.coin_info()
                content = coin
                replyMsg = reply.TextMsg(toUser, fromUser, content)
                return replyMsg.send()
            else:
                print("暂且不处理")
                return "success"
        except:
            print("exception error!")
            return 0